/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.address;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class MailtoURIParser extends URIParserBase<MailtoURIImpl> {
    private static final Log logger = LogFactory.getLog(MailtoURIParser.class);

    MailtoURIParser() {
    }

    protected Log getLogger() {
        return logger;
    }

    public MailtoURIImpl parse(byte[] uriData, int start, int end, MailtoURIImpl uriObject) throws ParseException {
        if (uriObject == null) uriObject = new MailtoURIImpl();
        start = ByteArrayUtil.firstMissing(uriData, ' ', start, end);
        end = ByteArrayUtil.lastMissing(uriData, ' ', start, end) + 1;
        final int schemaEnd = ByteArrayUtil.firstOccurence(uriData, ':', start, end);
        if (schemaEnd == -1)
            fail("The URI scheme cannot be recognized!", start);
        final String scheme = new String(uriData, start, schemaEnd - start);
        if (scheme.equals(""))
            fail("Malformed URI!", start);
        if (!scheme.equals("mailto"))
            fail("Unknown URI scheme: " + scheme, start);
        final int hostStart = ByteArrayUtil.firstOccurence(uriData, '@', schemaEnd + 1, end);
        if (hostStart == -1)
            throw new ParseException("The mailto URI is malformed!", schemaEnd + 1);
        uriObject.setUser(new String(uriData, schemaEnd+1, hostStart - schemaEnd -1));
        uriObject.setHost(new String(uriData, hostStart + 1, end - hostStart - 1));
        return uriObject;
    }
}
/*
 * $Log$
 */